package com.stone.im.geteway.netty;

import com.stone.im.geteway.dispather.DispatcherInstanceManger;
import com.stone.im.geteway.tcp.GatewayTcpHandler;
import com.stone.im.geteway.push.PushManager;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class GatewayTcpServer {

    private NioEventLoopGroup connectionThreadGroup;
    private NioEventLoopGroup ioThreadGroup;
    private ServerBootstrap server;
    ChannelFuture channelFuture;

    public static final int PORT = 8002;

    public GatewayTcpServer(){

        /**
         * 启动消息推送组件
         */
        //new PushManager().start();

        /**
         * 启动分发系统实例管理组件
         */
        DispatcherInstanceManger dispacherInstanceManger = DispatcherInstanceManger.getSingleton();
        dispacherInstanceManger.init();
        connectionThreadGroup = new NioEventLoopGroup();
        ioThreadGroup = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(connectionThreadGroup, ioThreadGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>(){
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ByteBuf delimiter = Unpooled.copiedBuffer("&_".getBytes());
                        socketChannel.pipeline().addLast(new GatewayTcpHandler());
                        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(4096,delimiter));
                    }
                });
    }

    @PostConstruct
    public void start(){
        this.channelFuture = server.bind(PORT);
        System.err.println("netty Tcp服务启动成功");
    }
}
